package com.zrz.controller;

import com.zrz.model.auto.Admin;
import com.zrz.model.auto.User;
import com.zrz.service.AdminService;
import com.zrz.service.UserService;
import com.zrz.util.LogUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class IndexController {
    @Value("${appId}")
    private String appId;
    @Value("${redirectUrl}")
    private String redirectUrl;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;

    @RequestMapping(value = "/redirect/index", method = RequestMethod.GET)
    public String redirect(HttpServletRequest request, HttpServletResponse response) {
        String url = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s?response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect", appId, redirectUrl + "/oauth/index");
        return "redirect:" + url;
    }

    @RequestMapping(value = "/oauth/index", method = RequestMethod.GET)
    public String oauth(HttpServletRequest request, HttpServletResponse response, Model model) {
//        String code = request.getParameter("code");
//        User user = userService.getUser(code);
//        if(user==null){
//            user=(User) request.getSession().getAttribute("user");
//            if(user==null){
//                return null;
//            }
//        }else {
//            request.getSession().setAttribute("user", user);
//        }
//        model.addAttribute("user", user);
        return "/index";
    }

    /**
     * 推广
     *
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "/oauth/extension", method = RequestMethod.GET)
    public String oauthExtension(HttpServletRequest request, HttpServletResponse response, Model model) {
        String code = request.getParameter("code");
        User user = userService.getUser(code);
//        User user=userService.getUser("obGGas1sMrvDuOrz-ILL94dyW-mY");
        if (user == null) {
            Integer userId = (Integer) request.getSession().getAttribute("userId");
            user=userService.getUserById(userId);
            if (user == null) {
                return null;
            }
        } else {
            request.getSession().setAttribute("userId", user.getId());
        }
//        String path = "/usr/local/QX_File/" + user.getId() + ".jpg";
//        String path = "d://58.jpg";
        String path="/usr/local/wine/image/"+user.getId()+".jpg";
//        String path="d://"+user.getId()+".jpg";
        String base64 = "data:image/jpg;base64," + getImgStr(path);
        model.addAttribute("imgBase64", base64);
        model.addAttribute("user", user);
        model.addAttribute("image", "/images/image/" + user.getId() + ".jpg");
        return "/extension";
    }

    /**
     * 会员
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/oauth/mine", method = RequestMethod.GET)
    public String oauthExtensionMine(HttpServletRequest request, HttpServletResponse response, Model model) {
        String code = request.getParameter("code");
        User user = userService.getUser(code);
        if (user == null) {
            Integer userId = (Integer) request.getSession().getAttribute("userId");
            user=userService.getUserById(userId);
            if (user == null) {
                return null;
            }
        } else {
            request.getSession().setAttribute("userId", user.getId());
        }
//        User user=userService.getUserById(175);
        model.addAttribute("user", user);
        return "/mine";
    }

    @RequestMapping(value = "/redirect/member", method = RequestMethod.GET)
    public String redirectMember(HttpServletRequest request, HttpServletResponse response) {
        String url = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s?response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect", appId, "http://5d3e8cfd.ngrok.io/oauth/index");
        return "redirect:/oauth/member";
    }

    @RequestMapping(value = "/oauth/addVip")
    public String member(HttpServletRequest request, HttpServletResponse response, Model model) {
        String code = request.getParameter("code");
        User user = userService.getUser(code);
        if (user == null) {
            Integer userId = (Integer) request.getSession().getAttribute("userId");
            user=userService.getUserById(userId);
            if (user == null) {
                return null;
            }
        } else {
            request.getSession().setAttribute("userId", user.getId());
        }
//        User user=userService.getUserById(197);

        model.addAttribute("user", user);
        model.addAttribute("status",user.getMember());
        model.addAttribute("mobile",user.getMobile());
        return "/member";
    }

    @RequestMapping(value = "/index")
    public String index() {
        return "/index";
    }

    @RequestMapping(value = "/member")
    public String member(HttpServletRequest request,Model model) {
        String code = request.getParameter("code");
        User user = userService.getUser(code);
        if (user == null) {
            Integer userId = (Integer) request.getSession().getAttribute("userId");
            user=userService.getUserById(userId);
            if (user == null) {
                return null;
            }
        } else {
            request.getSession().setAttribute("userId", user.getId());
        }
        return "/member";
    }

    private String getImgStr(String imgFile) {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(Base64.encodeBase64(data));
    }

    @RequestMapping(value = "/extension", method = RequestMethod.GET)
    public String extension(HttpServletRequest request, HttpServletResponse response, Model model) {
        model.addAttribute("image", "/images/image/53.jpg");
        return "/extension";
    }

    @RequestMapping(value = "/shopInfo")
    public String shopInfo(Model model,Integer id) {
        Admin admin=adminService.getAdmin(id);
       model.addAttribute("adminInfo",admin);
        return "shopInfo";
    }

    @RequestMapping(value = "/map")
    public String mapTest() {
        return "mapTest";
    }

    @RequestMapping(value = "/oauth/addBusiness", method = RequestMethod.GET)
    public String addBusiness(HttpServletRequest request, HttpServletResponse response, Model model) {
        String code = request.getParameter("code");
        User user = userService.getUser(code);
//        User user=userService.getUserById(32);
        request.getSession().setAttribute("mallUser", user);
        request.getSession().setAttribute("userId", user.getId());
        model.addAttribute("mallUser",user);
        if(user.getIsBusiness()){
            return "/addBusSuccess";
        }else {
            return "/agreement";
        }
    }
}
